import axios from 'axios'
import qs from 'qs'
import {useAppStore} from '@/store/modules/app'
import router from "@/router";
import { message } from 'ant-design-vue';

let lod;
// const router = useRouter()
const store = useAppStore()

const instance = axios.create({
  baseURL: '/api',
  timeout: 20000,
  transformRequest: [function (data) {
    return qs.stringify(data)
  }]
})

instance.interceptors.request.use(function (config) {
  if (!lod) {
    lod = message.loading('快马加鞭...', 0);
  }
  config.headers.common.Authorization = `Bearer ${store.token}`
  return config
}, function (error) {
  return Promise.reject(error)
})

instance.interceptors.response.use(function (response) {
  if (lod) {
    lod()
    lod = null
  }
  if (response.status === 200) {
    if (response.data.code === 200) {
      return Promise.resolve(response.data.data)
    } 
    if (response.data.code === 501) {
      store.clearData()
      router.push({path: '/login'})
      return false
    }

    alert(response.data.message)
  }
  return Promise.reject(response.data)
}, function (error) {
  return Promise.reject(error)
})

export default instance
